# -*- coding: utf-8 -*-

import os
import cgi
import urllib
import sys

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import *
from google.appengine.api import users
from google.appengine.ext.db import Key
from google.appengine.ext.db import BadKeyError
from google.appengine.ext.webapp import template
from xml.dom import minidom
from django.utils import simplejson
from time import strftime

from baseclass import BaseHandler
from alisoft import AliSoftAPI
       
class MainPage(BaseHandler):
    def get(self):        
        template_values = {}        
        template_values['isp'] = self.getCookie('isp')
        template_values['ispuser'] = self.getCookie('ispuser')
        template_values['customer'] = self.getCookie('customer')                       
        self.outputTemplate(template_values, "main_view")
        
class Messenger(BaseHandler):
    def get(self):
        # get status of a wangwang user
        # 0 offline
        # 1 online
        # 2 invalid user
        # need wangwang installed for im.msg
        api = AliSoftAPI()
        req = api.getReq('alisoft.im.userstatus2')
        req['uid'] = '254477'
        req['site'] = 'wangwang'
        req['v'] = '6'
        req['format'] = 'xml'
        result = api.reqAndRspPlain(req)
        dom = minidom.parseString(result.content)
        node = dom.getElementsByTagName('script')
        # for im.msg
        #self.response.out.write(node[0].childNodes[0].data)
        self.response.out.write(result.content)      
        
class QueryUser(BaseHandler):
    def get(self):
        api = AliSoftAPI()
        req = api.getReq('taobao.user.get')
        req['v'] = '1.0'
        req['fields'] = "buyer_credit,seller_credit,created,nick,real_name,location.address"
        if self.request.get('alisoftuser'):
            req['nick'] = self.request.get('alisoftuser')
        else:
            req['nick'] = self.request.get('isp_username')
        req['format'] = 'json'
        result = api.reqAndRspPlain(req)
        template_values = {'info': str(result.headers.items())+"<hr>"+result.content}
        reqLogin = {'sip_appkey': api.appid,
                    'sip_apiname': 'taobao.user.get',
                    'sip_sessionid': api.sessionid,
                    'sip_redirecturl': self.request.url
                   }
        sign = api.__sign__(reqLogin)  
        url = "http://sip.alisoft.com/sip/login?sip_appkey=%(sip_appkey)s&sip_apiname=%(sip_apiname)s&sip_sessionid=%(sip_sessionid)s&sip_redirecturl=%(sip_redirecturl)s" % reqLogin
        url += "&sip_sign="+sign
        template_values['alisoftlogin'] = url
        jsonresult = simplejson.loads(result.content)
        try:            
            template_values['alisoftuser'] = jsonresult['rsp']['users'][0]
        except:
            template_values['msg'] = result.content
        self.outputTemplate(template_values, "user_view") 
        
"""        
        api = AliSoftAPI()
        api.mainurl = 'http://sip.alisoft.com/sip/sipService'
        req = api.getSIPReq('sip.user.isLogin')
        req['sip_userid'] = self.request.get('alisoftuserid')
        req['sip_usertoken'] = self.request.get('alisofttoken')
        req['sip_tokentype'] = 'session'            
        result = api.reqAndRspPlain(req)
        self.response.out.write(result.content+" "+str(result.headers.items()))
        
        
        if result.headers['sip_status']=='1004':
            reqLogin = {'sip_appkey': api.appid,
                        'sip_apiname': 'taobao.items.instock.get',
                        'sip_sessionid': api.sessionid,
                        'sip_redirecturl': 'http://localhost:8080/user'
                        }
            sign = api.__sign__(reqLogin)  
            url = "http://sip.alisoft.com/sip/login?sip_appkey=%(sip_appkey)s&sip_apiname=%(sip_apiname)s&sip_sessionid=%(sip_sessionid)s" % reqLogin
            url += "&sip_sign="+sign
            self.response.out.write("<a href="%s">Alisoft Login</a>" % url)
        else:
            self.response.out.write(result.headers['sip_status']+result.content)        
   """        

application = webapp.WSGIApplication([('/', MainPage),
                                      ('/msg',Messenger),
                                      ('/user',QueryUser)],
                                     debug=True)
    
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
  main()